#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
异常处理工具类
提供常用的异常处理工具函数
"""

import functools
import logging
from typing import Any, Callable, Optional, Type, Union
from .base_exceptions import (
    BrainWaveException, DeviceException, DeviceConnectionException,
    DeviceDataException, SignalProcessingException, FilterException,
    BrainStateException, ValidationException, SessionException,
    DatabaseException, ConfigurationException, APIException
)

class ExceptionUtils:
    """异常处理工具类"""
    
    @staticmethod
    def safe_execute(func: Callable, *args, default_return=None, exception_types: tuple = (Exception,), **kwargs) -> Any:
        """安全执行函数，捕获异常并返回默认值
        
        Args:
            func: 要执行的函数
            *args: 函数参数
            default_return: 异常时返回的默认值
            exception_types: 要捕获的异常类型
            **kwargs: 函数关键字参数
            
        Returns:
            函数执行结果或默认值
        """
        try:
            return func(*args, **kwargs)
        except exception_types as e:
            logging.warning(f"Safe execution failed for {func.__name__}: {str(e)}")
            return default_return
    
    @staticmethod
    def validate_not_none(value: Any, field_name: str, message: str = None) -> Any:
        """验证值不为None
        
        Args:
            value: 要验证的值
            field_name: 字段名
            message: 自定义错误消息
            
        Returns:
            验证通过的值
            
        Raises:
            ValidationException: 验证失败时抛出
        """
        if value is None:
            msg = message or f"{field_name} 不能为空"
            raise ValidationException(msg, field_name, value)
        return value
    
    @staticmethod
    def validate_type(value: Any, expected_type: Type, field_name: str, message: str = None) -> Any:
        """验证值的类型
        
        Args:
            value: 要验证的值
            expected_type: 期望的类型
            field_name: 字段名
            message: 自定义错误消息
            
        Returns:
            验证通过的值
            
        Raises:
            ValidationException: 验证失败时抛出
        """
        if not isinstance(value, expected_type):
            msg = message or f"{field_name} 必须是 {expected_type.__name__} 类型，实际类型: {type(value).__name__}"
            raise ValidationException(msg, field_name, value)
        return value
    
    @staticmethod
    def validate_range(value: Union[int, float], min_val: Union[int, float] = None, 
                      max_val: Union[int, float] = None, field_name: str = "value", 
                      message: str = None) -> Union[int, float]:
        """验证数值范围
        
        Args:
            value: 要验证的值
            min_val: 最小值
            max_val: 最大值
            field_name: 字段名
            message: 自定义错误消息
            
        Returns:
            验证通过的值
            
        Raises:
            ValidationException: 验证失败时抛出
        """
        if min_val is not None and value < min_val:
            msg = message or f"{field_name} 不能小于 {min_val}，当前值: {value}"
            raise ValidationException(msg, field_name, value)
        
        if max_val is not None and value > max_val:
            msg = message or f"{field_name} 不能大于 {max_val}，当前值: {value}"
            raise ValidationException(msg, field_name, value)
        
        return value
    
    @staticmethod
    def validate_session_id(session_id: str) -> str:
        """验证会话ID
        
        Args:
            session_id: 会话ID
            
        Returns:
            验证通过的会话ID
            
        Raises:
            SessionException: 验证失败时抛出
        """
        if not session_id or not isinstance(session_id, str) or len(session_id.strip()) == 0:
            raise SessionException("无效的会话ID", session_id)
        return session_id.strip()
    
    @staticmethod
    def create_device_error(message: str, port: str = None) -> DeviceException:
        """创建设备异常"""
        if "连接" in message or "connection" in message.lower():
            return DeviceConnectionException(message, port)
        elif "数据" in message or "data" in message.lower():
            return DeviceDataException(message)
        else:
            return DeviceException(message, "DEVICE_ERROR", {"port": port})
    
    @staticmethod
    def create_processing_error(message: str, step: str = None) -> SignalProcessingException:
        """创建信号处理异常"""
        if "滤波" in message or "filter" in message.lower():
            return FilterException(message, step)
        else:
            return SignalProcessingException(message, step)
    
    @staticmethod
    def retry_on_exception(max_retries: int = 3, delay: float = 1.0, 
                          exception_types: tuple = (Exception,)):
        """重试装饰器
        
        Args:
            max_retries: 最大重试次数
            delay: 重试间隔（秒）
            exception_types: 需要重试的异常类型
        """
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                import time
                last_exception = None
                
                for attempt in range(max_retries + 1):
                    try:
                        return func(*args, **kwargs)
                    except exception_types as e:
                        last_exception = e
                        if attempt < max_retries:
                            logging.warning(f"Function {func.__name__} failed (attempt {attempt + 1}/{max_retries + 1}): {str(e)}")
                            time.sleep(delay)
                        else:
                            logging.error(f"Function {func.__name__} failed after {max_retries + 1} attempts")
                            raise last_exception
                
                raise last_exception
            return wrapper
        return decorator

# 常用验证函数的快捷方式
validate_not_none = ExceptionUtils.validate_not_none
validate_type = ExceptionUtils.validate_type
validate_range = ExceptionUtils.validate_range
validate_session_id = ExceptionUtils.validate_session_id
safe_execute = ExceptionUtils.safe_execute